package com.cloud.rabbitmq.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class RabbitTemplateConfig {
    private static final Logger log = LoggerFactory.getLogger(RabbitTemplateConfig.class);
    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate=new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //推送到server回调
        rabbitTemplate.setConfirmCallback(
                (correlationData, ack, cause)
                        ->
                {
                    if (ack) {
                        System.out.println("消息发送确认成功");
                    } else {
                        System.out.println("消息发送确认失败:" + cause);
                        throw new RuntimeException("失败");
                    }
                    log.info("ConfirmCallback correlationData:{},ack:{},cause:{}",correlationData,ack,cause);
                }

        );

        //消息返回给生产者, 路由不到队列时返回给发送者  先returnCallback,再 confirmCallback
        rabbitTemplate.setReturnCallback(
                (message, replyCode, replyText, exchange, routingKey)
                        ->
                {
                    log.info("ReturnCallback message:{},replyCode:{},replyText:{},exchange:{},routingKey:{}", message,replyCode,replyText,exchange,routingKey);
                }
        );
        return rabbitTemplate;
    }

}
